Imports System.Text
Namespace Core
    Friend NotInheritable Class Utils
        Private Sub New()
            ' Just so the compiler doesnt create a default constructor.
        End Sub
        Friend Shared Function HexDump(bytes As Byte()) As String
            If bytes Is Nothing Then
                Return "<null>"
            End If
            Dim len As Integer = bytes.Length
            '           1         2         3         4         5         6         7         8
            ' 012345678901234567890123456789012345678901234567890123456789012345678901234567890
            ' 12345678  00 11 22 33 44 55 66 77  88 99 AA BB CC DD EE FF  0123456789ABCDEF<<
            Dim result As New StringBuilder(((len + 15) \ 16) * 76)
            Dim chars As Char() = New Char(77) {}
            ' fill all with blanks
            For i As Integer = 0 To 74
                chars(i) = " "c
            Next
            chars(76) = ControlChars.Cr
            chars(77) = ControlChars.Lf

            For i1 As Integer = 0 To len - 1 Step 16
                chars(0) = HexChar(i1 >> 28)
                chars(1) = HexChar(i1 >> 24)
                chars(2) = HexChar(i1 >> 20)
                chars(3) = HexChar(i1 >> 16)
                chars(4) = HexChar(i1 >> 12)
                chars(5) = HexChar(i1 >> 8)
                chars(6) = HexChar(i1 >> 4)
                chars(7) = HexChar(i1 >> 0)

                Dim offset1 As Integer = 11
                Dim offset2 As Integer = 60

                For i2 As Integer = 0 To 15
                    If i1 + i2 >= len Then
                        chars(offset1) = " "c
                        chars(offset1 + 1) = " "c
                        chars(offset2) = " "c
                    Else
                        Dim b As Byte = bytes(i1 + i2)
                        chars(offset1) = HexChar(b >> 8)
                        chars(offset1 + 1) = HexChar(b)
                        chars(offset2) = (If(b < 32, "·"c, ChrW(b)))
                    End If
                    offset1 += (If(i2 = 8, 4, 3))
                    offset2 += 1
                Next
                result.Append(chars)
            Next
            Return result.ToString()
        End Function
        Private Shared Function HexChar(value As Integer) As Char
            value = value And &HF
            If value >= 0 AndAlso value <= 9 Then
                Return CChar("0"c + CStr(value))
            Else
                Return CChar("A"c + CStr(value - 10))
            End If
        End Function
    End Class
End Namespace
